from google.appengine.ext import db

from lib.webapp import app,  MJRequestHandler
from os.path import join

from lib.journey import Journey

import sys
import logging

import lib.regions as r
from lib.webapp import app


log = logging.getLogger(__name__)

class ctl_MyJourney(MJRequestHandler):

  path = "/myjourney"

  def load_region(self):  
    log.debug( "enter load_region" )
    regions = dict()
    region = self.request.get( "region", None )
    regions[0] = self.request.get( "region0", None )
    regions[1] = self.request.get( "region1", None )
    regions[2] = self.request.get( "region2", None )
    
    if( region == None or region == "" ):
        log.debug( "no region, search in tree" )
        for rl in range(2,-1,-1):
            log.debug( "    search in %d" % rl )
            if( regions[rl] != None ):
                log.debug( "   found!" )
                region = regions[rl]
                break
                
        if( region == None or region == "" ):
            return True
            
    def load( rkey ):                
        try:
            log.debug( "load region for %s" % rkey )
            rout = db.GqlQuery( "select * from Region where __key__ = :1", db.Key(rkey)  ).fetch(1)[0]
            log.debug( "    loaded" )
            return rout
        except:
            self.redirect( "/error?msg=Wrong region key" )
            return None

    self.c.j.region = load( region )
    
    if( self.c.j.region == None ):
        return False

    log.debug( "check region" )
    if( self.c.j.region.check_tree( regions[0], regions[1], regions[2] ) ):
        return True

    log.debug( "check region2" )

    for rl in range(2,-1,-1):
        log.debug( "   check in %d" % rl )
        if( regions[rl] != None ):
            self.c.j.region = load( regions[rl] )
                    
            if( self.c.j.region == None ):
                return False
            
            if( self.c.j.region.check_tree( regions[0], regions[1], regions[2] ) ):
                return True
    log.debug( "leaving load_region" )
    return True

  def index(self):
      
    """ show my journeys """
    
#    self.c.journeys = db.GqlQuery("SELECT * FROM Journey order by modified desc")
    self.c.journeys = db.GqlQuery( "select * from Journey where user = :1 order by user, modified desc", self.user ).fetch(50)
    
    return(self.render("/en/myjourney.html"))

  def new(self):
      
    """ show form for a new journey """

    self.c.j = Journey()
    self.c.regions = r.load_regions_for(None)
        
    return(self.render("/en/editmyjourney.html"))


  def save(self):
      
    log.debug( """ save journey """ )

    
    name = self.request.get( "name", None )
    desc = self.request.get( "desc", None )
    started = self.request.get( "started", None )
    ended = self.request.get( "ended", None )
    key = self.request.get( "journey", None )
    public = self.request.get( "public", None )
    length = self.request.get( "length", None )
    action = self.request.get( "action", None )

    log.debug( "name = %s" % name )
    log.debug( "desc = %s" % desc )
    
    if( key != None ):
        try:    
            self.c.j = db.GqlQuery( "select * from Journey where __key__ = :1", db.Key(key) ).fetch(1)[0]
            if( self.c.j.user != self.user ):
                self.redirect("/myjourney")
                return
                
            self.c.edit = True
        except:
            self.c.j = Journey()
    else:
        self.c.j = Journey()
 
    if( not self.load_region() ):
        return
   
    if( len(name) > 30 ):
        self.c.errors = True
        self.c.msg["Name length"] = "only 30 characters are allowed!"
    
    try:    
        self.c.j.name = name
    except:
        self.c.errors = True
        self.c.msg["Name"] = "line breaks are not allowed!"
        
    if( len(desc) > 500 ):
        self.c.errors = True
        self.c.msg["Description length"] = "only 500 characters are allowed!"
        desc = desc[0:499]
        
    self.c.j.desc = desc
     
    self.c.j.started = self.to_date( started, "Started on" )
    self.c.j.ended   = self.to_date( ended,   "Finished on" )
    
    self.c.j.length = length.strip()
    
    if( public == "on" ):
        self.c.j.public = True
                
#    print "name = %s"  %  self.c.j.name  
    if( self.c.j.name == None or self.c.j.name == "" ):
        self.c.req.name = True
        self.c.errors = True
        self.c.msg["Name"] = "required!"
  
    if( self.c.errors ):
        return(self.render("/en/editmyjourney.html"))

    if( action ):
        self.c.j.put()
            
        log.debug( "new journey with the key %s" % self.c.j.key )
        self.redirect("/myjourney/view?journey=%s" % self.c.j.key())

    self.c.regions = r.load_regions_for(self.c.j.region)

    return(self.render("/en/editmyjourney.html"))
            
  def view(self):

    key = self.request.get( "journey", None )
        
    log.debug( "requested journey with key %s" % key )

    try:    
        self.c.j = db.GqlQuery( "select * from Journey where __key__ = :1", db.Key(key) ).fetch(1)[0]
        self.c.edit = True
    except:
        log.warn( "error while retrieving journey" )
        self.redirect("/myjourney")
        return 

    if( self.user != self.c.j.user and not self.c.j.public ):
        self.redirect("/")
        return 
        
    if( self.c.j == None ):
        self.redirect("/myjourney")
        return
        
    return(self.render("/en/viewmyjourney.html"))

  def georsssimple(self):

    key = self.request.get( "journey", None )
        
    log.debug( "requested journey with key %s" % key )

    try:    
        self.c.j = db.GqlQuery( "select * from Journey where __key__ = :1", db.Key(key) ).fetch(1)[0]
        self.c.edit = True
    except:
        log.warn( "error while retrieving journey" )
        self.redirect("/myjourney")
        return 

    if( self.user != self.c.j.user and not self.c.j.public ):
        self.redirect("/")
        return 
        
    if( self.c.j == None ):
        self.redirect("/myjourney")
        return
        
    return(self.render("/georsssimple.xml"))

      
  def edit(self):

    key = self.request.get( "journey", None )
        
    log.debug( "requested journey with key %s" % key )

    try:    
        self.c.j = db.GqlQuery( "select * from Journey where __key__ = :1", db.Key(key) ).fetch(1)[0]
        self.c.edit = True
        if( self.c.j.user != self.user ):
            self.redirect( "/myjourney/view?journey=%s" % key )
            return
    except:
        log.warn( "error while retrieving journey" )
        self.redirect("/myjourney")
        return 
        
    if( self.c.j == None ):
        self.redirect("/myjourney")
        return

    self.c.regions = r.load_regions_for(self.c.j.region)
    
        
    return(self.render("/en/editmyjourney.html"))

  def __init__(self):
      
        MJRequestHandler.__init__(self)
      
        self.add_handler( "/new",  self.new )
        self.add_handler( "/save", self.save )
        self.add_handler( "/view", self.view, False )
        self.add_handler( "/edit", self.edit )
        self.add_handler( "/georsssimple", self.georsssimple, False )
        
    


app().add_handler( ctl_MyJourney.path + ".*", ctl_MyJourney )
